'use strict';

angular.module('afasApp')
  .controller('CourseSchedulesCtrl', ['$scope', '$rootScope', 'Services', '$state', '$filter', function ($scope, $rootScope, Services, $state, $filter) {

    // var fn = makeService('Terms');
    // $scope.terms = $injector.instantiate(fn).getItems;

    // VARIABLE
    $scope.courseschedules = [];
    $scope.courses = [];
    $scope.coursetypes = [];
    $scope.terms = [];
    $scope.timeclasses = [];
    $scope.dayclasses = [];
    $scope.classrooms = [];
    $scope.courseArray = [];
    $scope.courseScheduleNew = {};
    $scope.termSelected = false;
    $scope.psForm = false;
    $scope.psFormEdit = false;
    $scope.psStudent = false;
    $scope.students = [];
    $scope.staffs = [];
    $scope.showResults = false;
    $scope.selectedCourse = {};
    $scope.isId = false;
    $scope.isNat = false;
    $scope.isCom = false;
    $scope.localTeachers = [];
    $scope.nativeTeachers = [];
    $scope.errors = {};

    $scope.newEnrollment = {};
    $scope.params = {
      'term_number': 1,
      'term_year': new Date().getFullYear(),
      'course_type': '',
      'include': 'all,paid_enrollment_count,enrollment_count',
      'getall': 'true'
    };

    $scope.attemptTry = 0;

    // COURSE TYPES
    Services.getItems($scope.COURSETYPE_URL)
    .then(function(results){
      $scope.coursetypes = results.data;
      var CTylsd = _.findWhere($scope.coursetypes, {Id: 1});
      var CTylsmp = _.findWhere($scope.coursetypes, {Id: 4});
      var CTge = _.findWhere($scope.coursetypes, {Id: 2});
      var CTkk = _.findWhere($scope.coursetypes, {Id: 3});

      $scope.coursetypes = [];
      $scope.coursetypes.push(CTylsd);
      $scope.coursetypes.push(CTylsmp);
      $scope.coursetypes.push(CTge);
      $scope.coursetypes.push(CTkk);
      $scope.params.course_type = $scope.coursetypes[0].Id;

    });

    Services.getItems('terms', {'select': 'current'})
    .then(function(results){
      // console.log(results.data);
      var currentTerm = _.filter(results.data, function(obj) {
        return obj.CourseType.Id === 2;
      });
      $scope.params.term_number = currentTerm[0].Number;
      $scope.params.term_year = currentTerm[0].Year;
      // $scope.params.course_type = currentTerm[0].CourseType.Id;
    })

    // Services.getItems($scope.TIMECLASS_URL)
    // .then(function(results){
    //   $scope.timeclasses = results.data;
    //   var formDate = [
    //     {
    //       'OriginalProp': 'StartTime',
    //       'ExpectedProp': 'OrderTime'
    //     }
    //   ];
    //   $scope.timeclasses = $filter('takeTime')($scope.timeclasses, formDate);
    //   $scope.timeclasses = $filter('orderBy')($scope.timeclasses, 'OrderTime');
    // });

    // Services.getItems($scope.DAYCLASS_URL)
    // .then(function(results){
    //   $scope.dayclasses = results.data;
    // });

    Services.getItems('classrooms', { 'getall': true })
    .then(function(results){
      $scope.classrooms = results.data;
    });

    $scope.searchStudent = function() {
      var params = {
        'is_valid': true,
        'keyword': $scope.keyword,
        'include': 'all'
      };
      Services.getItems('students', params)
      .then(function(results){
        $scope.students = results.data;
        $scope.showResults = true;
      });
    };

    $scope.addStudent = function(csID){
      $scope.newEnrollment.CourseSchedule = {};
      $scope.newEnrollment.CourseSchedule.Id = csID;
      $scope.psStudent = true;
    };

    $scope.selectThis = function(student) {
      $scope.newEnrollment.Student = {};
      // $scope.newEnrollment.CourseCompletionStatus = {};
      $scope.newEnrollment.Student.Id = student;
      $scope.newEnrollment.CourseCompletionStatus = 0;

      // console.log($scope.newEnrollment);
      Services.add('enrollments', $scope.newEnrollment)
      .then(function(){
        $scope.newEnrollment = {};
        $scope.showResults = false;
        $scope.psStudent = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    function reFormat() {
      $scope.courseArray = [];


      angular.forEach($scope.courseschedules, function(value, key){
        value.SequenceForOrder = value.Course.CourseLevel.Sequence;
        value.SuffixForOrder = value.Suffix;

        if (value.Staffs.length > 1) {
          if (value.SigningTeacher == value.Staffs[1].Id) {
            var teacherTemp = value.Staffs[0];
            value.Staffs[0] = value.Staffs[1];
            value.Staffs[1] = teacherTemp;
          };
        };

      });

      var teachType = [];
      teachType[0] = _.filter($scope.courseschedules, function(obj) {
        return obj.Course.TeacherType === 1;
      });
      teachType[1] = _.filter($scope.courseschedules, function(obj) {
        return obj.Course.TeacherType === 2;
      });
      teachType[2] = _.filter($scope.courseschedules, function(obj) {
        return obj.Course.TeacherType === 0;
      });

      angular.forEach($scope.timeclasses, function(valueA, keyA){
        $scope.courseArray[valueA.Id] = [];
        angular.forEach($scope.dayclasses, function(valueB, keyB){

          this[valueA.Id][valueB.Id] = [];

          this[valueA.Id][valueB.Id][0] = {};
          this[valueA.Id][valueB.Id][0].status = 0;
          this[valueA.Id][valueB.Id][0].title = 'IND';
          this[valueA.Id][valueB.Id][0].value = 1;
          this[valueA.Id][valueB.Id][0].content = [];

          this[valueA.Id][valueB.Id][1] = {};
          this[valueA.Id][valueB.Id][1].status = 0;
          this[valueA.Id][valueB.Id][1].title = 'COM';
          this[valueA.Id][valueB.Id][1].value = 2;
          this[valueA.Id][valueB.Id][1].content = [];

          this[valueA.Id][valueB.Id][2] = {};
          this[valueA.Id][valueB.Id][2].status = 0;
          this[valueA.Id][valueB.Id][2].title = 'NAT';
          this[valueA.Id][valueB.Id][2].value = 0;
          this[valueA.Id][valueB.Id][2].content = [];

        }, this);
      }, $scope.courseArray);

      for (var courseIndex = 2; courseIndex >= 0; courseIndex--) {
        angular.forEach(teachType[courseIndex], function(value, key){
          // console.log(value);
          if (typeof this[value.TimeClass.Id] != 'undefined') {
            this[value.TimeClass.Id][value.DayClass.Id][courseIndex].status = 1;
            var content = value;
            this[value.TimeClass.Id][value.DayClass.Id][courseIndex].content.push(content);
          }
        }, $scope.courseArray);


        angular.forEach($scope.timeclasses, function(valueA, keyA){
          angular.forEach($scope.dayclasses, function(valueB, keyB){
            // console.log(this);

            $filter('orderBy')(this[valueA.Id][valueB.Id][courseIndex].content, ['SequenceForOrder', 'SuffixForOrder']);

          }, this);
        }, $scope.courseArray);

      };

    }

    $scope.label=function (start, end) {
      return $filter('date')(start, 'hh:mm a')+' - '+$filter('date')(end, 'hh:mm a');
    };

    // $scope.addCourseSchedule = function () {
    $scope.submitSchedule = function () {
      // console.log($scope.courseNew);
      $scope.courseScheduleNew.Term = {
        'Id': $scope.courseScheduleNew.Term.Id
      }
      var CS = [];
      CS.push($scope.courseScheduleNew);
      Services.add($scope.COURSESCHEDULE_URL, CS)
      .then(function(results){
        // $scope.courseScheduleNew = {};
        angular.forEach(results.data, function(value, key){
          $scope.courseschedules.push(value);
        });
        reFormat();

        $scope.psForm = false;
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };

    $scope.deleteCourseSchedule = function (course) {
      Services.delete($scope.COURSESCHEDULE_URL, course)
      .then(function(){
      });
    };

    $scope.resetTable = function () {
      $scope.termSelected = false;
    };

    $scope.callTerm = function () {

      var paramCourse = {
        'course_type': $scope.filterTable.CourseType.Id,
        'order_by': 'year',
        'order_type': 'desc',
        'getall': true
      };

      Services.getItems('terms', paramCourse)
      .then(function( results ) {
        $scope.terms = results.data;
      });
    };

    $scope.nextTerm = function () {
      $scope.params.term_number = parseInt($scope.params.term_number)+1;
      $scope.showTable($scope.params.course_type, 2);
    }

    $scope.prevTerm = function () {
      $scope.params.term_number = parseInt($scope.params.term_number)-1;
      $scope.showTable($scope.params.course_type, 1);
    }

    $scope.showTable = function (CtId, showType) {
      $scope.termSelected = true;
      $scope.timeclasses = [];
      $scope.dayclasses = [];

      $scope.params.course_type = CtId;

      $scope.courseScheduleNew.Term = {};

      var paramDayClasses = {
        'include': 'course_type',
        'getall': true
      };

      var paramTimeClasses = {
        'include': 'course_type',
        'getall': true
      };

      Services.getItems($scope.DAYCLASS_URL, paramDayClasses)
      .then(function( results ) {
        $scope.dayclasses = results.data;
        $scope.dayclasses = _.filter($scope.dayclasses, function(obj) {
          return obj.CourseType.Id === $scope.params.course_type;
        });
        $scope.dayclasses = _.sortBy($scope.dayclasses, function(obj){
          return obj.DayRange;
        });


        Services.getItems($scope.TIMECLASS_URL, paramTimeClasses)
        .then(function( results ) {
          $scope.timeclasses = results.data;
          $scope.timeclasses = _.filter($scope.timeclasses, function(obj) {
            return obj.CourseType.Id === $scope.params.course_type;
          });

          Services.getItems($scope.COURSESCHEDULE_URL, $scope.params)
          .then(function( results ) {
            $scope.courseschedules = results.data;

            switch(showType){
              case 1:
              if (($scope.courseschedules.length > 0) || ($scope.attemptTry > 1) ) {
                $scope.attemptTry = 0;
                reFormat();
              } else {
                $scope.attemptTry++;
                $scope.params.term_number = 5;
                $scope.params.term_year = parseInt($scope.params.term_year)-1;
                $scope.showTable(CtId, 1);
              }
              break;

              case 2:
              if (($scope.courseschedules.length > 0) || ($scope.attemptTry > 1) ) {
                $scope.attemptTry = 0;
                reFormat();
              } else {
                $scope.attemptTry++;
                $scope.params.term_number = 1;
                $scope.params.term_year = parseInt($scope.params.term_year)+1;
                $scope.showTable(CtId, 2);
              }
              break;

              case 0:
              $scope.attemptTry = 0;
              reFormat();
              break;
            }

          });
        });
      });
    };

    $scope.addSchedule = function (TimeClassId, DayClassId, TeacherTypeId) {
      $scope.errors = {};

      $scope.courseScheduleNew.TimeClass = {};
      $scope.courseScheduleNew.DayClass = {};

      var termParams = {
        'year': $scope.params.term_year,
        'number': $scope.params.term_number,
        'course_type': $scope.params.course_type
      }

      Services.getItems('terms', termParams)
      .then(function(results){
        $scope.courseScheduleNew.Term = results.data[0];
        $scope.courseScheduleNew.StartDate = results.data[0].StartDate;
        $scope.courseScheduleNew.EndDate = results.data[0].EndDate;
        // console.log($scope.courseScheduleNew.Term);
      });

      Services.getItem($scope.TIMECLASS_URL, TimeClassId)
      .then(function(results){
        $scope.courseScheduleNew.TimeClass = results.data;
      });

      Services.getItem($scope.DAYCLASS_URL, DayClassId)
      .then(function(results){
        $scope.courseScheduleNew.DayClass = results.data;
      });

      var paramCourse = {
        'course_type': $scope.params.course_type,
        'include': 'all',
        'getall': true
      };

      Services.getItems('courses', paramCourse)
      .then(function( results ) {
        $scope.courses = results.data;
        $scope.courses = _.filter($scope.courses, function(obj) {
          return obj.CourseLevel.CourseType.Id === $scope.params.course_type;
        });

        $scope.courses = _.where($scope.courses, {TeacherType: TeacherTypeId});

        // var ind = _.where($scope.courses, {TeacherType: 1});
        // var com = _.where($scope.courses, {TeacherType: 2});
        // var nat = _.where($scope.courses, {TeacherType: 0});

        // $scope.courses = [];
        // angular.forEach(ind, function(value, key){
        //   $scope.courses.push(value);
        // });
        // angular.forEach(com, function(value, key){
        //   $scope.courses.push(value);
        // });
        // angular.forEach(nat, function(value, key){
        //   $scope.courses.push(value);
        // });

        $scope.psForm = true;
      });

      // console.log($scope.courseScheduleNew);
    };

    $scope.maintainSchedule = function(Id, selectedCourse) {
      $scope.errors = {};
      $scope.selectedCourse = selectedCourse;
      var paramMaintain = {
        'include': 'enrollment_count,paid_enrollment_count,unpaid_enrollment_count,cancelled_enrollment_count,enrollments,all'
      };
      $scope.isId = false;
      $scope.isNat = false;
      Services.getItem('course_schedules', Id, paramMaintain)
      .then(function(results){
        $scope.psFormEdit = true;
        $scope.courseScheduleCurrent = results.data;

        console.log($rootScope.TeacherStaffTypes[$scope.courseScheduleCurrent.Course.TeacherType].Query);
        console.log($scope.courseScheduleCurrent.Course.TeacherType);

        if ($scope.courseScheduleCurrent.SigningTeacher == $scope.courseScheduleCurrent.Staffs[1].Id) {
          var teacherTemp = $scope.courseScheduleCurrent.Staffs[0];
          $scope.courseScheduleCurrent.Staffs[0] = $scope.courseScheduleCurrent.Staffs[1];
          $scope.courseScheduleCurrent.Staffs[1] = teacherTemp;
        };

        Services.getItems('staffs', {'getall': true, 'is_valid': true, 'staff_type': $rootScope.TeacherStaffTypes[$scope.courseScheduleCurrent.Course.TeacherType].Query})
        .then(function(results){
          $scope.staffs = results.data;

          switch($scope.courseScheduleCurrent.Course.TeacherType){
            case 0:
              $scope.isId = false;
              $scope.isNat = true;
              $scope.isCom = false;
              break;
            case 1:
              $scope.isId = true;
              $scope.isNat = false;
              $scope.isCom = false;
              break;
            case 2:
              $scope.isId = false;
              $scope.isNat = false;
              $scope.isCom = true;
              break;
            };

            $scope.localTeachers = _.filter($scope.staffs, function(obj) {
              return obj.StaffType === 1;
            });

            $scope.nativeTeachers = _.filter($scope.staffs, function(obj) {
              return obj.StaffType === 2;
            });
        });
      })
    };

    $scope.updateSchedule = function(schedule) {
      $scope.errors = {};
      // $scope.courseScheduleCurrent.SigningTeacher = $scope.courseScheduleCurrent.Staffs[1].Id;
      if ($scope.isCom) {
        $scope.courseScheduleCurrent.SigningTeacher = $scope.courseScheduleCurrent.Staffs[0].Id;
      };
      Services.update('course_schedules', $scope.courseScheduleCurrent, $scope.courseScheduleCurrent.Id)
      .then(function(results){
        schedule = results.data;
        $scope.psFormEdit = false;
        $scope.showTable($scope.params.course_type, 0);
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    };
  }])
  .controller('ClassListsCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', function($scope, Services, $state, $stateParams, $filter, _){

    var currentTerm = [];
    $scope.courseschedules = [];
    $scope.coursetypes = [];
    $scope.terms = [];
    $scope.term = {};
    $scope.filterTable = {
      'CourseType': {}
    };
    $scope.params = {
      'getall': true,
      // 'include': 'enrollment_count,paid_enrollment_count,unpaid_enrollment_count,cancelled_enrollment_count,staffs,terms'
      'include': 'all,enrollment_count,paid_enrollment_count,unpaid_enrollment_count,cancelled_enrollment_count,staffs,terms'
    };
    $scope.validation = [];
    $scope.coba = true;
    $scope.cobacoba = "blablabalblala,balsdlas,,asjdlasdka";

    $scope.attemptTry = 0;

    Services.getItems('course_types')
    .then(function(results){
      $scope.coursetypes = results.data;

      if ($stateParams.course) {
        $scope.filterTable.CourseType.Id = parseInt($stateParams.course);
        $scope.callTerm();
      };
    });

    if (!$stateParams.course) {
      Services.getItems('terms', {'select': 'current'})
      .then(function(results){
        currentTerm = _.filter(results.data, function(obj) {
          return obj.CourseType.Id === 2;
        });
        $scope.filterTable.CourseType.Id = currentTerm[0].CourseType.Id;
        $scope.params.term = currentTerm[0].Id;

        $scope.callTerm();
      })
    };

    // PAGINATION
    // $scope.pagesize = 10;

    // $scope.pagination = {
    //   current: 1
    // };

    // $scope.pageChanged = function(newPage) {
    //   getResultsPage(newPage);
    // };

    // function getResultsPage(pageNumber) {
    //   var data = $scope.params;
    //   data.pagesize = $scope.pagesize;
    //   data.page = (pageNumber - 1);
    //   $scope.pagination.current = pageNumber;
    //   Services.getItems('course_schedules', data)
    //   .then(function( results ) {
    //     var pagingData = angular.fromJson(results.headers['x-pagination']);
    //     $scope.totalItems = pagingData.TotalCount;
    //     $scope.courseschedules = results.data;
    //   });
    // };

    $scope.checkNextTerm = function () {
      var indexTerm = 0;
      _.find($scope.terms, function(val, key){
        if(val.Id == $scope.params.term){ indexTerm = key; return true;};
      });
      if ((indexTerm-1) > -1) {
        return false;
      } else {
        return true;
      }
    }

    $scope.nextTerm = function () {
      var indexTerm;
      _.find($scope.terms, function(val, key){
        if(val.Id == $scope.params.term){ indexTerm = key; return true;};
      });
      $scope.params.term = $scope.terms[indexTerm-1].Id;
      loadClass();
    };

    $scope.checkPrevTerm = function () {
      var indexTerm = 0;
      _.find($scope.terms, function(val, key){
        if(val.Id == $scope.params.term){ indexTerm = key; return true;};
      });

      if ((indexTerm+1) < ($scope.terms.length)) {
        return false;
      } else {
        return true;
      }
    }

    $scope.prevTerm = function () {
      var indexTerm;
      _.find($scope.terms, function(val, key){
        if(val.Id == $scope.params.term){ indexTerm = key; return true;};
      });
      $scope.params.term = $scope.terms[indexTerm+1].Id;
      loadClass();
    };

    function loadClass() {
      Services.getItems('course_schedules', $scope.params)
      .then(function( results ) {
        // $scope.totalItems = pagingData.TotalCount;
        $scope.courseschedules = results.data;

        angular.forEach($scope.courseschedules, function(value, key){
          value.SequenceForOrder = value.Course.CourseLevel.Sequence;
          value.SuffixForOrder = value.Suffix;
          switch(value.Course.TeacherType){
            case 1:
              value.TeacherTypeForOrder = 'a';
              break;
            case 2:
              value.TeacherTypeForOrder = 'b';
              break;
            case 0:
              value.TeacherTypeForOrder = 'c';
              break;
          }
        });

        $scope.courseschedules = $filter('orderBy')($scope.courseschedules, ['SequenceForOrder', 'SuffixForOrder', 'TeacherTypeForOrder']);

        $scope.term = _.findWhere($scope.terms, {Id: $scope.params.term});

      });
    }

    $scope.searchClass = function() {
      $state.go( '^.searchList', {'course': $scope.filterTable.CourseType.Id, 'term': $scope.params.term} );
    };

    $scope.callTerm = function () {

      var paramCourse = {
        'course_type': $scope.filterTable.CourseType.Id,
        'order_by': 'Year',
        'order_type': 'DESC',
        'getall': true
      };

      Services.getItems('terms', paramCourse)
      .then(function( results ) {
        $scope.terms = results.data;
        $scope.terms = $filter('orderBy')($scope.terms, ['Year', 'Number'], true);

        if ($stateParams.term) {
          $scope.params.term = parseInt($stateParams.term);

          // getResultsPage(1);
          loadClass();
        };
        if (currentTerm[0]) {
          // getResultsPage(1);
          loadClass();
        };
      });
    };
  }])
  .controller('RaffledCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', function($scope, Services, $state, $stateParams, $filter, _){

    $scope.items = [];
    $scope.item = {};
    $scope.filterTable = {};

    $scope.callTerm = function () {

      var paramCourse = {
        'year': $scope.filterTable.Year,
        'number': $scope.filterTable.Number,
        'course_types': '1,2,4',
        'include': 'enrollments',
        'getall': true
      };

      Services.getItems('terms', paramCourse)
      .then(function( results ) {
        angular.forEach(results.data, function(val, key){
          $scope.items.push(val.enrollments);
        });
      });
    };

    $scope.handleRadioRaffled = function(item) {
      angular.forEach($scope.items, function(value, key){
        // console.log(value);
        $scope.items[key].IsBestStudentRaffled = false;
      });
      item.IsBestStudentRaffled = true;
      $scope.item = item;
    };

    $scope.save = function(){
      Services.update('enrollments', $scope.item, $scope.item.Id)
      .then(function(results){
        console.log(results.data);
      });
      // Services.update('enrollments', allEnrollments)
      // .then(function(results){
      //   console.log(results.data);
      // });
    };
  }])
  .controller('ClassAssessmentCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', function($scope, Services, $state, $stateParams, $filter, _){

    $scope.coursechedule = {};
    $scope.enrollments = [];
    $scope.subjects = [];
    $scope.enrollments = [];
    $scope.commentEnrollment = {};
    $scope.commentForm = false;

    $scope.assessments = [];

    var paramMaintain = {
      'include': 'all,enrollment_count,paid_enrollment_count,unpaid_enrollment_count,cancelled_enrollment_count,enrollments'
    };

    Services.getItem('course_schedules', $stateParams.id, paramMaintain)
    .then(function(results){
      $scope.courseschedule = results.data;
    });

    Services.getItems('enrollments', {'getall': true, 'course_schedule': $stateParams.id, 'include': 'all,student'})
    .then(function(results){
      $scope.enrollments = _.filter(results.data, function(obj) {
        // console.log(obj.Invoice);
        return obj.CourseCompletionStatus !== 6;
      });
      angular.forEach($scope.enrollments, function(object, key){
        object.StudentNameForOrder = object.Student.FullName;
      });
      angular.forEach($scope.enrollments, function(object, key){
        angular.forEach(object.Assessments, function(assessment, assessmentKey){
          assessment.OrderForOrder = assessment.Subject.Order;
        });
        object.Assessments = $filter('orderBy')(object.Assessments, 'OrderForOrder');
      });
      $scope.subjects = _.filter($scope.enrollments[0].Assessments, function(obj) {
        // console.log(obj.Invoice);
        return obj.Subject.IsActive === true;
      });
      // angular.forEach($scope.enrollments, function(value, key){
      //   $scope.assessments[value.Id] = [];
      //   var asses = [];
      //   angular.forEach(value.Assessments, function(valAss, keyAss){
      //     if (valAss.Subject.IsActive) {
      //       var ass = {
      //         'Score': valAss.Score,
      //         'ByMakeUpTest': valAss.ByMakeUpTest,
      //         'Enrollment': {
      //           'Id': value.Id
      //         },
      //         'Subject': {
      //           'Id': valAss.Subject.Id,
      //           'IsActive': valAss.Subject.IsActive // quick fix - Dodok
      //         }
      //       };
      //       // asses.push(ass);
      //       asses[valAss.Subject.Id] = ass;
      //     };
      //   });
      //   $scope.assessments[value.Id] = asses;
      // });
    });

    $scope.cleanActive = function (items){
      items = _.filter(items, function(obj) {
        // console.log(obj.Invoice);
        return obj.Subject.IsActive === true;
      });
      return items;
    };

    $scope.handleRadioBestStudent = function(item) {
      angular.forEach($scope.enrollments, function(value, key){
        // console.log(value);
        $scope.enrollments[key].IsBestStudent = false;
      });
      item.IsBestStudent = true;
    };

    $scope.handleRadioRaffled = function(item) {
      angular.forEach($scope.enrollments, function(value, key){
        // console.log(value);
        $scope.enrollments[key].IsBestStudentRaffled = false;
      });
      item.IsBestStudentRaffled = true;
    };

    $scope.calculateTotal = function(enrollment){
      var TotalScore = 0;
      var Assessments = _.filter(enrollment.Assessments, function(obj) {
        return obj.Subject.IsActive === true;
      });
      angular.forEach(Assessments, function(value, key){
        console.log(value.Score);
        TotalScore = TotalScore + parseInt(value.Score);
      });
      enrollment.TotalScore = TotalScore;
    };

    $scope.openComment = function (enrollment) {
      $scope.commentEnrollment = enrollment;
      $scope.commentForm = true;
    };

    $scope.save = function(enrollment){
      // var assessment = [];
      // angular.forEach($scope.assessments[index], function(valAss, keyAss){
      //   if (valAss && valAss.Subject.IsActive == true) { // quick fix - Dodok
      //     assessment.push(valAss);
      //   };
      // });
      // Services.add('assessments', assessment)
      // .then(function(results){
      //   console.log(results.data);
      // });
      // var enrollment = _.findWhere($scope.enrollments, {Id: index});

      var enroll = {};
      // angular.copy(enrollment, enroll);
      // delete enroll.Assessments;

      Services.update('enrollments', enrollment, enrollment.Id)
      .then(function(results){
        enrollment.TotalScore = results.data.TotalScore;
      });
    };

    $scope.saveAll = function(){
      var allAssessments = [];
      // angular.forEach($scope.assessments, function(value, key){
      //   angular.forEach(value, function(valAss, keyAss){
      //     if (valAss && valAss.Subject.IsActive == true) { // quick fix - Dodok
      //       allAssessments.push(valAss);
      //     };
      //   });
      // });
      // Services.add('assessments', allAssessments)
      // .then(function(results){
      //   console.log(results.data);
      // }, function(results){
      //   console.log(results);
      //   if (results.status == 400) {
      //     $scope.errors = results.data;
      //   }
      // });

      angular.forEach($scope.enrollments, function(value, key){
        var enroll = {};
        // angular.copy(value, enroll);
        // delete enroll.Assessments;
        Services.update('enrollments', value, value.Id)
        .then(function(results){
          value.TotalScore = results.data.TotalScore;
        });
      })
      // Services.update('enrollments', allEnrollments)
      // .then(function(results){
      //   console.log(results.data);
      // });
    };
  }])
  .controller('ClassInfoCtrl', ['$scope', '$rootScope', 'Services', '$stateParams', '$state', '$filter', '_', function($scope, $rootScope, Services, $stateParams, $state, $filter, _){

    $scope.coursechedule       = {};
    $scope.enrollments         = [];
    $scope.registered          = [];
    $scope.waitingList         = [];
    $scope.cancelled           = [];
    $scope.selectedEnrollments = [];
    $scope.courselevel         = {};
    $scope.cancelForm          = false;
    $scope.moveForm            = false;
    $scope.cancelBatchForm     = false;
    $scope.moveBatchForm       = false;
    $scope.refundMoveChecked   = false;

    $scope.terms = [];

    $scope.refundCancel  = {
      'Enrollment': {},
      'RefundInitiator': 0,
      'Amount': 0,
      'Type': {},
      'Status': 1
    };
    $scope.refundMove    = {
      'Enrollment': {},
      'RefundInitiator': 0,
      'Amount': 0,
      'Type': {},
      'Status': 1,
      'TotalTemp': 0
    };

    $scope.refundCancelBatch  = [];
    $scope.refundMoveBatch    = [];
    $scope.refundMoveBatchCourseScheduleTarget = {};
    $scope.schedules = [];
    $scope.moveSchedules = [];
    $scope.refundTypes   = [];
    $scope.refundReal = 0;

    var paramMaintain = {
      'include': 'enrollment_count,paid_enrollment_count,unpaid_enrollment_count,cancelled_enrollment_count,all',
      'getall': true
    };

    Services.getItems('refund_types')
    .then(function(results){
      $scope.refundTypes = results.data;
    });

    Services.getItem('course_schedules', $stateParams.id, paramMaintain)
    .then(function(results){
      $scope.courseschedule = results.data;

      Services.getItem('course_levels', $scope.courseschedule.Course.CourseLevel.Id, {'include': 'all'})
      .then(function(results){
        $scope.courselevel = results.data;

      });

    });

    Services.getItems('enrollments', {'course_schedule': $stateParams.id, 'include': 'all,student', 'getall': true})
    .then(function(results){
      $scope.enrollments = results.data;
      var registeredA = _.filter($scope.enrollments, function(obj) {
        // console.log(obj.Invoice);
        return (obj.Invoice && obj.Invoice.InvoiceStatus === 1 && obj.CourseCompletionStatus !== 6);
      });
      var registeredB = _.filter($scope.enrollments, function(obj) {
        return (obj.Invoice && obj.Invoice.InvoiceStatus === 2 && obj.CourseCompletionStatus !== 6);
        // return _.where(obj.Invoice, {InvoiceStatus: 2}).length > 0;
      });
      $scope.registered = _.union(registeredA, registeredB);
      // $scope.waitingList = _.findDeep($scope.enrollments, {'InvoiceStatus': '0'});
      $scope.waitingList = _.filter($scope.enrollments, function(obj) {
        return (obj.Invoice && obj.Invoice.InvoiceStatus === 0);
      });
      $scope.cancelled = _.filter($scope.enrollments, function(obj) {
        return (obj.CourseCompletionStatus === 6);
      });
      $scope.registered = _.sortBy($scope.registered, function (obj) {
        return obj.Student.FullName;
      });
      $scope.waitingList = _.sortBy($scope.waitingList, function (obj) {
        return obj.Student.FullName;
      });
      $scope.cancelled = _.sortBy($scope.cancelled, function (obj) {
        return obj.Student.FullName;
      });
      // $scope.waitingList = _.where($scope.enrollments, {InvoiceStatus: '0'});
    });

    $scope.cancelClass = function(enroll){
      $scope.errors = {};
      $scope.refundCancel.date_time = moment().format('YYYY-MM-DD');
      Services.getItem('enrollments', enroll.Id, {'include': 'refundable_status', 'refund_request_date': $scope.refundCancel.date_time})
      .then(function(results) {
        $scope.cancelForm = true;
        $scope.refundCancel.IsRefundable = results.data.IsRefundable;
        $scope.refundCancel.Type = results.data.RefundType;
        $scope.refundCancel.NominalTemp = Math.abs($scope.refundCancel.Type.Nominal);
        $scope.refundCancel.Enrollment = enroll;
      });
    };

    $scope.checkRefundCancel = function() {
      Services.getItem('enrollments', $scope.refundCancel.Enrollment.Id, {'include': 'refundable_status', 'refund_request_date': $scope.refundCancel.date_time})
      .then(function(results) {
        $scope.refundCancel.IsRefundable = results.data.IsRefundable;
        $scope.refundCancel.Type = results.data.RefundType;
        $scope.refundCancel.NominalTemp = Math.abs($scope.refundCancel.Type.Nominal);
      });
    };

    $scope.$watch('timepicker.timeA', function(newValue, oldValue){
      var dateRaw = moment(newValue);
      var dateSend = dateRaw.format('YYYY-MM-DD');
      $scope.refundCancel.date_time = dateSend;
      $scope.refundMove.date_time = dateSend;
      $scope.refundCancelBatchDateTime = dateSend;
      $scope.refundMoveBatchDateTime = dateSend;
    });

    $scope.submitCancellation = function(){
      if ($scope.refundCancel.IsRefundable) {
        $scope.refundCancel.RefundRequestDate = $filter('date')($scope.timepicker.timeA, 'yyyy-MM-dd');
        Services.add('refunds', $scope.refundCancel)
        .then(function(results){
          console.log(results.data);
          // $state.go('refund.move', {id: id});
          $scope.errors.MessageType = 'alert-success';
          $scope.errors.Message = 'Successfully Cancelled';
          $scope.cancelForm = false;
        }, function(results){
          if (results.status == 400) {
            $scope.errors = results.data;
            $scope.errors.MessageType = 'alert-danger';
          }
        });
      };
    };

    $scope.moveClass = function(enroll){
      $scope.errors = {};
      $scope.refundMove.date_time = moment().format('YYYY-MM-DD');
      $scope.moveForm = true;
      $scope.refundMove.Enrollment = enroll;
      $scope.moveSchedules = [];
    };

    $scope.loadTerm = function() {
      $scope.moveSchedules = [];

      // Services.getItems('terms', {'select': 'current', 'include': 'course_schedules', 'course_type': $scope.courselevel.CourseType.Id})
      // .then(function(results){
      //   // var terms = [];
      //   var currentTerm = results.data[0];

      //   // LOAD COURSE SCHEDULES
      //   var paramCourse = {
      //     'term': currentTerm.Id,
      //     'include': 'all,enrollment_count',
      //     'getall' : true
      //   };

      //   Services.getItems($scope.COURSESCHEDULE_URL, paramCourse)
      //   .then(function( results ) {
      //     var schedules = [];
      //     schedules = results.data;
      //     schedules = _.filter(schedules, function(obj) {
      //       return (obj.Course.CourseLevel.Id === $scope.courseschedule.Course.CourseLevel.Id);
      //     });

      //     angular.forEach(schedules, function(valSchedule, keySchedule){
      //       valSchedule.TypeGroup = $rootScope.formatTerm(currentTerm) + ' (Current Term)';
      //       valSchedule.IsCurrentTerm = true;
      //       $scope.moveSchedules.push(valSchedule);
      //     });
      //   });
      // });

      Services.getItems('terms', {'getall': true, 'select': 'next', 'reference_date': $scope.refundMove.date_time, 'include': 'course_schedules', 'course_type': $scope.courselevel.CourseType.Id})
      .then(function(results){
        var terms = [];
        terms = results.data;
        angular.forEach(terms, function(value, key){
          angular.forEach(value.CourseSchedules, function(valueB, keyB){
            valueB.TypeGroup = $rootScope.formatTerm(value);
            valueB.IsCurrentTerm = false;
            $scope.moveSchedules.push(valueB);
          });
        });
        $scope.moveSchedules = _.filter($scope.moveSchedules, function(obj) {
          return (obj.Course.CourseLevel.Id === $scope.courseschedule.Course.CourseLevel.Id);
        });

      });
    }

    $scope.checkRefundMove = function() {
      Services.getItem('enrollments', $scope.refundMove.Enrollment.Id, {'include': 'refundable_status', 'refund_request_date': $scope.refundMove.date_time, 'course_schedule_target': $scope.refundMove.CourseScheduleTarget.Id})
      .then(function(results) {
        $scope.refundMove.IsRefundable = results.data.IsRefundable;
        $scope.refundMove.Type = results.data.RefundType;
        $scope.refundMove.NominalTemp = Math.abs($scope.refundMove.Type.Nominal);
      });
    };

    $scope.submitMutation = function(){
      if ($scope.refundMove.IsRefundable) {
        $scope.refundMove.RefundRequestDate = $filter('date')($scope.timepicker.timeA, 'yyyy-MM-dd');
        Services.add('refunds', $scope.refundMove)
        .then(function(results){
          console.log(results.data);
          // $state.go('refund.move', {id: id});
          $scope.errors.MessageType = 'alert-success';
          $scope.errors.Message = 'Successfully Moved';
          $scope.moveForm = false;
        }, function(results){
          if (results.status == 400) {
            $scope.errors = results.data;
            $scope.errors.MessageType = 'alert-danger';
          }
        });
      };
    };

    $scope.label = function(value){
      return $filter('date')(value.StartTime, 'HH:mm') + '-' + $filter('date')(value.EndTime, 'HH:mm');
    };

    $scope.balanceCancel = function () {
      if ($scope.refundCancel.Enrollment.Invoice) {
        return ($scope.refundCancel.Enrollment.Invoice.TotalAmount - $scope.refundCancel.Enrollment.Invoice.TotalDiscount) - ((($scope.refundCancel.Enrollment.Invoice.TotalAmount - $scope.refundCancel.Enrollment.Invoice.TotalDiscount)*($scope.refundCancel.Type.Percentage/100)) - $scope.refundCancel.Type.Nominal);
      };
    }

    $scope.balanceMove = function () {
      if ($scope.refundMove.CourseScheduleTarget) {
        return $scope.refundMove.CourseScheduleTarget.Course.CourseFee.Fee - (($scope.refundMove.Enrollment.Invoice.TotalAmount - $scope.refundMove.Enrollment.Invoice.TotalDiscount) - ( ($scope.refundMove.CourseScheduleTarget.IsCurrentTerm) ? 0 : ((($scope.refundMove.Type.Percentage/100) * ($scope.refundMove.Enrollment.Invoice.TotalAmount - $scope.refundMove.Enrollment.Invoice.TotalDiscount)) + $scope.refundMove.Type.Nominal)));
      };
    };

    $scope.cancelClassBatch = function(){
      $scope.errors = {};
      $scope.cancelBatchForm = true;
      $scope.refundCancelBatchDateTime = moment().format('YYYY-MM-DD');
      $scope.refundCancelBatch = [];

      angular.forEach($scope.selectedEnrollments, function(value, key){
        Services.getItem('enrollments', value.Id, {'include': 'refundable_status', 'refund_request_date': $scope.refundCancelBatchDateTime})
        .then(function(results) {

          var batch  = {
            'Enrollment': value,
            'RefundInitiator': 0,
            'Amount': 0,
            'Type': results.data.RefundType,
            'Status': 1,
            'Note': '',
            'IsRefundable': results.data.IsRefundable,
            'NominalTemp': 0
          };
          $scope.refundCancelBatch.push(batch);
        });
      });
    };

    $scope.checkRefundCancelBatch = function() {

      angular.forEach($scope.refundCancelBatch, function(value, key){
        Services.getItem('enrollments', value.Enrollment.Id, {'include': 'refundable_status', 'refund_request_date': $scope.refundCancelBatchDateTime})
        .then(function(results) {
          value.IsRefundable = results.data.IsRefundable;
          value.Type = results.data.RefundType;
          value.NominalTemp = Math.abs(results.data.RefundType.Nominal);
        });
      });

    };

    $scope.balanceCancelBatch = function (refundCancel) {
      if (refundCancel.Enrollment.Invoice) {
        if (refundCancel.IsRefundable) {
          return (refundCancel.Enrollment.Invoice.TotalAmount - refundCancel.Enrollment.Invoice.TotalDiscount) - (((refundCancel.Enrollment.Invoice.TotalAmount - refundCancel.Enrollment.Invoice.TotalDiscount)*(refundCancel.Type.Percentage/100)) - refundCancel.Type.Nominal);
        };
      };
    };

    $scope.submitCancellationBatch = function(){
      var iterationBatch = 0;
      var completedBatch = 0;
      angular.forEach($scope.refundCancelBatch, function(value, key){
        if (value.IsRefundable) {
          iterationBatch++;
          value.RefundRequestDate = $filter('date')($scope.timepicker.timeA, 'yyyy-MM-dd');
          Services.add('refunds', value)
          .then(function(results){
            completedBatch++;
            if (iterationBatch == completedBatch) {
              $scope.errors.MessageType = 'alert-success';
              $scope.errors.Message = 'Successfully Cancelled';
              $scope.cancelBatchForm = false;
            };
          }, function(results){
            if (results.status == 400) {
              $scope.errors = results.data;
              $scope.errors.MessageType = 'alert-danger';
            }
          });
        };
      });
    };

    $scope.moveClassBatch = function(){
      $scope.errors = {};
      $scope.moveBatchForm = true;
      $scope.refundMoveBatchDateTime = moment().format('YYYY-MM-DD');
      $scope.refundMoveBatch = [];

      angular.forEach($scope.selectedEnrollments, function(value, key){
        var batch  = {
          'Enrollment': value,
          'RefundInitiator': 0,
          'Amount': 0,
          'Type': {},
          'Status': 1,
          'Note': '',
          'IsRefundable': false,
          'NominalTemp': 0
        };
        $scope.refundMoveBatch.push(batch);
      });
    };

    $scope.checkRefundMoveBatch = function() {

      angular.forEach($scope.refundMoveBatch, function(value, key){
        Services.getItem('enrollments', value.Enrollment.Id, {'include': 'refundable_status', 'refund_request_date': $scope.refundMoveBatchDateTime, 'course_schedule_target': $scope.refundMoveBatchCourseScheduleTarget.Id})
        .then(function(results) {
          value.IsRefundable = results.data.IsRefundable;
          value.Type = results.data.RefundType;
          value.NominalTemp = Math.abs(results.data.RefundType.Nominal);
        });
      });

    };

    $scope.balanceMoveBatch = function (refundMove) {
      if ($scope.refundMoveBatchCourseScheduleTarget.Id) {
        return $scope.refundMoveBatchCourseScheduleTarget.Course.CourseFee.Fee - ((refundMove.Enrollment.Invoice.TotalAmount - refundMove.Enrollment.Invoice.TotalDiscount) - ( ($scope.refundMoveBatchCourseScheduleTarget.IsCurrentTerm) ? 0 : (((refundMove.Type.Percentage/100) * (refundMove.Enrollment.Invoice.TotalAmount - refundMove.Enrollment.Invoice.TotalDiscount)) + refundMove.Type.Nominal)));
      };
    };

    $scope.submitMutationBatch = function(){
      var iterationBatch = 0;
      var completedBatch = 0;
      angular.forEach($scope.refundMoveBatch, function(value, key){
        if (value.IsRefundable) {
          iterationBatch++;
          value.CourseScheduleTarget = $scope.refundMoveBatchCourseScheduleTarget;
          value.RefundRequestDate = $filter('date')($scope.timepicker.timeA, 'yyyy-MM-dd');
          Services.add('refunds', value)
          .then(function(results){
            completedBatch++;
            if (iterationBatch == completedBatch) {
              $scope.errors.MessageType = 'alert-success';
              $scope.errors.Message = 'Successfully Moveled';
              $scope.cancelBatchForm = false;
            };
          }, function(results){
            if (results.status == 400) {
              $scope.errors = results.data;
              $scope.errors.MessageType = 'alert-danger';
            }
          });
        };
      });
    };

    $scope.checkSelected = function(Id) {
      return _.where($scope.selectedEnrollments, { Id: Id }).length > 0;
    };

    $scope.toggleRefund = function(enrollment) {
      console.log(enrollment);
      var items = _.where($scope.selectedEnrollments, {Id: enrollment.Id});
      var item = _.findWhere($scope.selectedEnrollments, {Id: enrollment.Id});

      if (items.length > 0) {
        $scope.selectedEnrollments = _.without($scope.selectedEnrollments, item);
      } else {
        $scope.selectedEnrollments.push(enrollment);
      }
    };

    // $scope.$watch('refundCancel.Type', function(newValue, oldValue){
    //   $scope.refundReal = newValue.Nominal;
    // });

    // $scope.$watch('refundMove.CourseScheduleTarget', function(newValue, oldValue){

    //   $scope.refundMove.TotalTemp = Math.abs($scope.refundMove.CourseScheduleTarget.Course.CourseFee.Fee - (($scope.refundMove.Enrollment.Invoice.TotalAmount + $scope.refundMove.Enrollment.Invoice.TotalDiscount) - (($scope.refundMove.Type.Percentage/100) * ($scope.refundMove.Enrollment.Invoice.TotalAmount + $scope.refundMove.Enrollment.Invoice.TotalDiscount)) - $scope.refundMove.Type.Nominal));
    // });
  }])
  .controller('ClassIdsCtrl', ['$scope', 'Services', '$stateParams', '$state', '$filter', '_', function($scope, Services, $stateParams, $state, $filter, _){

    $scope.coursechedule = {};
    $scope.enrollments   = [];
    $scope.registered    = [];
    $scope.waitingList   = [];
    $scope.cancelled     = [];
    $scope.cancelForm    = false;
    $scope.moveForm      = false;
    $scope.refundCancel  = {
      'Enrollment': {},
      'RefundInitiator': 0
    };
    $scope.refundMove    = {};
    $scope.refundTypes   = [];
    $scope.refundNominal = 100000;
    $scope.refundReal = 0;

    var paramMaintain = {
      'include': 'all,term,classroom,course,course_level,day_class,time_class,staffs'
    };

    Services.getItems('refund_types')
    .then(function(results){
      $scope.refundTypes = results.data;
    });

    Services.getItem('course_schedules', $stateParams.id, paramMaintain)
    .then(function(results){
      $scope.courseschedule = results.data;
    });

    Services.getItems('enrollments', {'course_schedule': $stateParams.id, 'include': 'all,student,last_placement_test,refundable_status', 'getall': true})
    .then(function(results){
      $scope.enrollments = results.data;
      var registeredA = _.filter($scope.enrollments, function(obj) {
        // console.log(obj.Invoice);
        return (obj.Invoice && obj.Invoice.InvoiceStatus === 1);
      });
      var registeredB = _.filter($scope.enrollments, function(obj) {
        return (obj.Invoice && obj.Invoice.InvoiceStatus === 2);
        // return _.where(obj.Invoice, {InvoiceStatus: 2}).length > 0;
      });
      $scope.registered = _.union(registeredA, registeredB);
      // $scope.waitingList = _.findDeep($scope.enrollments, {'InvoiceStatus': '0'});
      $scope.waitingList = _.filter($scope.enrollments, function(obj) {
        return (obj.Invoice && obj.Invoice.InvoiceStatus === 0);
      });
      $scope.cancelled = _.filter($scope.enrollments, function(obj) {
        return (obj.CourseCompletionStatus === 6);
      });
      // $scope.waitingList = _.where($scope.enrollments, {InvoiceStatus: '0'});
    });

    $scope.cancelClass = function(refund, id){
      $scope.cancelForm = true;
      $scope.refundCancel.Type = refund;
      $scope.refundCancel.Amount = $scope.refundNominal-($scope.refundNominal*($scope.refundCancel.Type.Percentage/100));
      $scope.refundCancel.Amount = $scope.refundCancel.Amount + $scope.refundCancel.Type.Nominal;
      $scope.refundCancel.Enrollment.Id = id;
      // var data = {
      //   'CourseCompletionStatus': 6
      // };

      // Services.update('enrollments', data, id)
      // .then(function(results){
      //   $state.go('refund.cancel', {id: id});
      // });
    };

    $scope.submitCancellation = function(){
      Services.add('refunds', $scope.refundCancel)
      .then(function(results){
        console.log(results.data);
        // $state.go('refund.move', {id: id});
      }, function(results){
        if (results.status == 400) {
          $scope.errors = results.data;
        }
      });
    }

    $scope.moveClass = function(id){
      $scope.moveForm = true;
      // var data = {
      //   'CourseCompletionStatus': 6
      // };

      // Services.update('enrollments', data, id)
      // .then(function(results){
      //   $state.go('refund.move', {id: id});
      // });
    };

    $scope.$watch('refundCancel.Type', function(newValue, oldValue){
      console.log(newValue);
      console.log(nominal);
      nominal = nominal + newValue.Nominal;
      console.log(nominal);
      $scope.refundReal = nominal;
    });
  }])
  .controller('CourseScheduleCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', function ($scope, Services, $state, $stateParams, $filter) {

    $scope.currentCourse = {};

    $scope.courses = [];
    $scope.terms = [];
    $scope.timeclasses = [];
    $scope.dayclasses = [];
    $scope.rooms = [];

    $scope.currentID = $stateParams.id;
    // $scope.currencies = Currencies.getCurrencies();
    // $scope.coursetypes = CourseTypes.getCourseTypes();
    $scope.currentCourseSchedule = {};


    $scope.label=function (start, end) {
      return $filter('date')(start, 'HH:mm')+' - '+$filter('date')(end, 'HH:mm');
    };

    Services.getItem($scope.COURSESCHEDULE_URL, $scope.currentID)
    .then(function(results){
      $scope.currentCourseSchedule = results.data;
    });


    Services.getItems('courses', { 'getall': true, 'include': 'all' })
    .then(function(results){
      $scope.courses = results.data;
    });

    Services.getItems('terms', { 'getall': true })
    .then(function(results){
      $scope.terms = results.data;
    });

    Services.getItems($scope.TIMECLASS_URL, { 'getall': true })
    .then(function(results){
      $scope.timeclasses = results.data;
    });

    Services.getItems($scope.DAYCLASS_URL, { 'getall': true })
    .then(function(results){
      $scope.dayclasses = results.data;
    });

    Services.getItems('classrooms', { 'getall': true })
    .then(function(results){
      $scope.rooms = results.data;
    });


    $scope.calculate = function (valueCur, currency) {
      if (currency) {
        $scope.conversionResult = valueCur * $scope.currencies[currency].RupiahRate;
        $scope.conversionResult = $filter('currency')($scope.conversionResult, 'Rp ');
      }
    };

    $scope.updateCourseSchedule = function () {
      Services.update($scope.COURSESCHEDULE_URL, $scope.currentCourseSchedule, $scope.currentID)
      .then(function(results){
        console.log(results);
        // $state.go( 'courses.show', {id: $scope.currentID} );
        $state.go( '^.list');
      });
      // Courses.updateCourse($scope.currentCourse, $scope.currentID);
    };
  }])
  .controller('CourseScheduleTeachersCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', 'Teachers', 'Courses', 'TimeClasses', 'DayClasses', 'Rooms', 'Terms', function ($scope, Services, CourseSchedules, $state, $stateParams, $filter, Teachers, Courses, TimeClasses, DayClasses, Rooms, Terms) {

    $scope.days = [
      { id: 0, label: 'Monday', selected: false },
      { id: 1, label: 'Tuesday', selected: false },
      { id: 2, label: 'Wednesday', selected: false },
      { id: 3, label: 'Thursday', selected: false },
      { id: 4, label: 'Friday', selected: false },
      { id: 5, label: 'Saturday', selected: false },
      { id: 6, label: 'Sunday', selected: false }
    ];

    $scope.currentCourseSchedule = {};
    $scope.currentID = $stateParams.id;
    $scope.teachers = Teachers.getTeachers();
    $scope.classrooms = Rooms.getRooms();
    $scope.courses = Courses.getCourses();
    $scope.terms = Terms.getTerms();
    $scope.timeclasses = TimeClasses.getTimeClasses();
    $scope.dayclasses = DayClasses.getDayClasses();
    $scope.currentCourseSchedule =CourseSchedules.getCourseSchedule($stateParams.id);
    $scope.teachersNew = null;
    if (!$scope.currentCourseSchedule.Teachers) {
      $scope.currentCourseSchedule.Teachers = [];
    }

    $scope.updateCourseSchedule = function () {
      CourseSchedules.updateCourseSchedule($scope.currentCourseSchedule, $scope.currentID);
      $scope.teachersNew = null;
      // $state.go( 'courses.show', {id: $scope.currentID} );
    };

    $scope.addTeacher = function () {
      // console.log($scope.courseNew);
      $scope.currentCourseSchedule.Teachers.push($scope.teachersNew);
      $scope.updateCourseSchedule();
    };

    $scope.deleteTeacher = function (index) {
      $scope.currentCourseSchedule.Teachers.splice(index, 1);
      $scope.updateCourseSchedule();
    };
  }])
  .controller('CourseScheduleActivitiesCtrl', ['$scope', 'Services', '$state', '$stateParams', '$filter', '_', function ($scope, Services, $state, $stateParams, $filter, _ ) {

    $scope.courseschedule = {};
    $scope.enrollments = [];
    $scope.subjects = [];
    $scope.currentId = $stateParams.id;
    $scope.params = {
      'include': 'all,course_activities'
    };

    Services.getItem('course_schedules', $scope.currentId, $scope.params)
    .then(function(results){
      $scope.courseschedule = results.data;
    });

    Services.getItems('enrollments', {'course_schedule': $scope.currentId, 'include': 'all'})
    .then(function(results){
      $scope.enrollments = results.data;
      $scope.subjects = $scope.enrollments[0].Assessments;
    });
  }]);